package com.funmi.lizip.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.base.ResultCode;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.File;
import com.funmi.lizip.entity.dto.file.FileAddRequest;
import com.funmi.lizip.entity.dto.file.FileQueryRequest;
import com.funmi.lizip.entity.dto.file.FileUpdateRequest;
import com.funmi.lizip.entity.vo.FileVo;
import com.funmi.lizip.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@Api(tags = "文档")
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;



    @ApiOperation(value = "文档的新增")
    @PostMapping("")
    public R addFile(@RequestBody FileAddRequest request) {
        if (request == null) {
            throw new ApplicationException(ResultCode.NOT_FOUND);
        }

        File file = new File();
        request.setCreateAt(LocalDateTime.now());
        BeanUtils.copyProperties(request, file);
        boolean save = fileService.save(file);
        if (save) {
            return R.success().message("新增成功");
        } else {
            throw new ApplicationException("新增失败");
        }
    }

    @ApiOperation(value = "文档的修改")
    @PutMapping("/{id}")
    public R updateFile(@RequestBody(required = false) FileUpdateRequest request) {
        if (request == null || request.getId() == null) {
            throw new ApplicationException(ResultCode.NOT_FOUND);
        }
        File file = new File();
        BeanUtils.copyProperties(request, file);
        boolean update = fileService.updateById(file);

        if (update) {
            return R.success().message("修改成功");
        } else {
            throw new ApplicationException("修改失败");
        }
    }

    @ApiOperation(value = "文档的删除")
    @DeleteMapping("/{id}")
    public R deleteFile(@PathVariable int id) {
        if (id <= 0) {
            throw new ApplicationException(ResultCode.ID_NOT_FOUND);
        }
        boolean result = fileService.removeById(id);
        if (result) {
            return R.success().message("删除成功");
        } else {
            return R.fail().message("删除失败");
        }
    }

    @ApiOperation(value = "根据输入进行检索")
    @GetMapping("")
    public R queryList(FileQueryRequest request) {
        long current = 1;
        long size = 10;
        File fileQuery = new File();
        if (request != null) {
            BeanUtils.copyProperties(request, fileQuery);
            current = request.getPage();
            size = request.getPageSize();
        }

        QueryWrapper<File> qw = new QueryWrapper<>(fileQuery);
        qw.select().orderByDesc("create_at");
        Page<File> filePage = fileService.page(new Page<>(current, size), qw);

        PageDTO<FileVo> fileVoPage = new PageDTO(filePage.getCurrent(), filePage.getSize(), filePage.getTotal());

        List<FileVo> fileVoList = filePage.getRecords().stream().map(file -> {
            FileVo fileVo = new FileVo();
            BeanUtils.copyProperties(file, fileVo);
            return fileVo;
        }).collect(Collectors.toList());

        fileVoPage.setRecords(fileVoList);
        return R.success().data(fileVoPage);
    }


    @ApiOperation(value = "文件的上传")
    @PostMapping("/upload")
    public static R upload(MultipartFile file, String destFilePath) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            inputStream = file.getInputStream();
            // 数据缓冲
            byte[] buffer = new byte[1024 * 1024];
            //读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
           // File tempFile = new File(destFilePath);
            java.io.File tempFile = new java.io.File(destFilePath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            //重新命名
            fileName = Math.random() +"."+ split[split.length-1];
            fileOutputStream = new FileOutputStream(tempFile.getPath() + java.io.File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            return R.success().data(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                fileOutputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.success().message("上传成功");
    }
//    public R upLoad(@RequestParam("file") MultipartFile file) {
//
//        try {
//            // 获取文件名字
//            String filename = file.getOriginalFilename();
//            // 获取后缀名 .jpg
//            String substring = filename.substring(filename.lastIndexOf("."));
//
//            // 重新生成文件名
//            String uuidName = UUID.randomUUID() + substring; // fsdf.jpg
//
//            // 指定文件夹作为存储图片位置
//            String filePath = "D:/Develop";
//
//            java.io.File dir = new java.io.File("D:/Develop");
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//
//            file.transferTo(new java.io.File(filePath + uuidName));
//            return R.success().message("上传成功");
//        } catch (IOException e) {
//            e.printStackTrace();
//            return R.fail();
//        }
//
//
//    }
}
